<template>
  <view class="map-container">
	  <status-bar></status-bar>
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
        <text class="iconfont icon-back">&lt;</text>
      </view>
      <view class="nav-title">选择位置</view>
      <view class="nav-right" @click="confirmLocation">
        <text>确定</text>
      </view>
    </view>
    
    <!-- 搜索框 -->
    <view class="search-box">
      <view class="search-input-wrap">
        <text class="search-icon">🔍</text>
        <input 
          type="text" 
          class="search-input" 
          placeholder="搜索地点" 
          v-model="searchKeyword"
          @confirm="searchLocation"
        />
        <text class="clear-icon" v-if="searchKeyword" @click="clearSearch">×</text>
      </view>
    </view>
    
    <!-- 地图组件 -->
    <map
      id="myMap"
      class="map"
      :latitude="latitude"
      :longitude="longitude"
      :markers="markers"
      :scale="scale"
      show-location
      @regionchange="onRegionChange"
      @tap="onMapTap"
    ></map>
    
    <!-- 中心点标记 -->
    <view class="center-marker">
      <view class="marker-pin"></view>
    </view>
    
    <!-- 定位按钮 -->
    <view class="location-btn" @click="getCurrentLocation">
      <text class="location-btn-icon">📍</text>
    </view>
    
    <!-- 位置信息面板 -->
    <view class="location-panel">
      <view class="current-location">
        <view class="location-icon">📍</view>
        <view class="location-info">
          <view class="location-name">{{ locationName || '正在获取位置...' }}</view>
          <view class="location-address">{{ locationAddress || '请移动地图选择位置' }}</view>
        </view>
      </view>
      
      <!-- 位置列表 -->
      <scroll-view 
        class="location-list" 
        scroll-y 
        v-if="searchResults.length > 0"
      >
        <view 
          class="location-item" 
          v-for="(item, index) in searchResults" 
          :key="index"
          @tap="selectSearchResult(item)"
        >
          <view class="item-name">{{ item.name }}</view>
          <view class="item-address">{{ item.address }}</view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      latitude: 39.908823,  // 默认纬度（北京）
      longitude: 116.397470, // 默认经度（北京）
      scale: 16,            // 缩放级别
      markers: [],          // 地图标记点
      locationName: '',     // 当前位置名称
      locationAddress: '',  // 当前位置地址
      searchKeyword: '',    // 搜索关键词
      searchResults: [],    // 搜索结果列表
      selectedLocation: null, // 选中的位置
      isGettingLocation: false, // 是否正在获取位置
      province: '',         // 省份
      city: '',             // 城市
      district: ''          // 区县
    }
  },
  onLoad(options) {
    // 获取页面参数
    if (options.latitude && options.longitude) {
      this.latitude = parseFloat(options.latitude);
      this.longitude = parseFloat(options.longitude);
    } else {
      // 获取当前位置
      this.getCurrentLocation();
    }
  },
  onReady() {
    // 地图组件初始化完成后，获取当前位置信息
    this.getLocationInfo(this.latitude, this.longitude);
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    // 获取当前位置
    getCurrentLocation() {
      if (this.isGettingLocation) return;
      
      this.isGettingLocation = true;
      uni.showLoading({ title: '定位中...' });
      
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          this.getLocationInfo(res.latitude, res.longitude);
          
          // 更新地图视图
          const mapContext = uni.createMapContext('myMap');
          mapContext.moveToLocation({
            latitude: res.latitude,
            longitude: res.longitude
          });
        },
        fail: (err) => {
          console.error('获取位置失败:', err);
          uni.showToast({
            title: '获取位置失败，请检查定位权限',
            icon: 'none'
          });
        },
        complete: () => {
          this.isGettingLocation = false;
          uni.hideLoading();
        }
      });
    },
    // 获取位置信息
    getLocationInfo(latitude, longitude) {
      // 这里应该调用地图API获取位置信息
      // 由于uni-app中没有直接的地理编码API，这里模拟一个
      // 实际项目中可以使用高德、腾讯、百度等地图API
      
      uni.showLoading({ title: '获取位置信息...' });
      
      // 模拟API调用 - 实际项目中替换为真实API调用
      setTimeout(() => {
        uni.hideLoading();
        
        // 模拟数据 - 实际项目中应该从API响应中获取
        this.locationName = this.generateLocationName(latitude, longitude);
        this.locationAddress = this.generateAddress(latitude, longitude);
        
        // 解析地址获取省市区信息
        const addressInfo = this.parseAddress(this.locationAddress);
        this.province = addressInfo.province;
        this.city = addressInfo.city;
        this.district = addressInfo.district;
        
        // 更新标记
        this.updateMarker(latitude, longitude);
      }, 800);
    },
    // 生成位置名称（模拟）
    generateLocationName(lat, lng) {
      // 实际项目中应该从地图API获取
      const locations = [
        '万达广场', '中央公园', '科技园', '商业中心', 
        '文化广场', '体育中心', '购物中心', '创业园区'
      ];
      const randomIndex = Math.floor(Math.random() * locations.length);
      return locations[randomIndex];
    },
    // 生成地址（模拟）
    generateAddress(lat, lng) {
      // 实际项目中应该从地图API获取
      const provinces = ['河北省', '北京市', '天津市'];
      const cities = ['石家庄市', '保定市', '北京市', '天津市'];
      const districts = ['桥西区', '鹿泉区', '新华区', '长安区', '海淀区', '朝阳区'];
      const streets = ['和平路', '建设大街', '中山路', '解放大道', '长安街'];
      
      const province = provinces[Math.floor(Math.random() * provinces.length)];
      const city = cities[Math.floor(Math.random() * cities.length)];
      const district = districts[Math.floor(Math.random() * districts.length)];
      const street = streets[Math.floor(Math.random() * streets.length)];
      const number = Math.floor(Math.random() * 200) + 1;
      
      return `${province}${city}${district}${street}${number}号`;
    },
    // 解析地址获取省市区信息
    parseAddress(address) {
      // 实际项目中应该使用更准确的解析方法或直接从API获取
      const result = {
        province: '',
        city: '',
        district: ''
      };
      
      // 简单的正则匹配
      const provinceMatch = address.match(/(.*?省|.*?市)(?=.*?市)/);
      if (provinceMatch) {
        result.province = provinceMatch[1];
      }
      
      const cityMatch = address.match(/(?:省|市)(.*?市)(?=.*?区|.*?县)/);
      if (cityMatch) {
        result.city = cityMatch[1];
      }
      
      const districtMatch = address.match(/(?:市)(.*?区|.*?县)/);
      if (districtMatch) {
        result.district = districtMatch[1];
      }
      
      // 如果匹配失败，使用默认值
      if (!result.province) result.province = '河北省';
      if (!result.city) result.city = '石家庄市';
      if (!result.district) result.district = '鹿泉区';
      
      return result;
    },
    // 更新地图标记
    updateMarker(latitude, longitude) {
      this.markers = [{
        id: 1,
        latitude: latitude,
        longitude: longitude,
        width: 30,
        height: 30,
        callout: {
          content: this.locationName,
          color: '#000000',
          fontSize: 14,
          borderRadius: 4,
          padding: 5,
          display: 'ALWAYS'
        }
      }];
    },
    // 地图区域变化事件
    onRegionChange(e) {
      if (e.type === 'end' && e.causedBy === 'drag') {
        // 获取地图中心点位置
        const mapContext = uni.createMapContext('myMap');
        mapContext.getCenterLocation({
          success: (res) => {
            this.latitude = res.latitude;
            this.longitude = res.longitude;
            this.getLocationInfo(res.latitude, res.longitude);
          }
        });
      }
    },
    // 点击地图事件
    onMapTap(e) {
      const { latitude, longitude } = e.detail;
      this.latitude = latitude;
      this.longitude = longitude;
      this.getLocationInfo(latitude, longitude);
    },
    // 搜索位置
    searchLocation() {
      if (!this.searchKeyword.trim()) return;
      
      // 这里应该调用地图API搜索位置
      // 由于uni-app中没有直接的地点搜索API，这里模拟一个
      // 实际项目中可以使用高德、腾讯、百度等地图API
      
      uni.showLoading({ title: '搜索中...' });
      
      // 模拟API调用 - 实际项目中替换为真实API调用
      setTimeout(() => {
        uni.hideLoading();
        
        // 模拟搜索结果 - 实际项目中应该从API响应中获取
        const results = [];
        for (let i = 0; i < 5; i++) {
          const latOffset = (Math.random() - 0.5) * 0.05;
          const lngOffset = (Math.random() - 0.5) * 0.05;
          
          results.push({
            name: `${this.searchKeyword}${i + 1}`,
            address: this.generateAddress(
              this.latitude + latOffset,
              this.longitude + lngOffset
            ),
            latitude: this.latitude + latOffset,
            longitude: this.longitude + lngOffset
          });
        }
        
        this.searchResults = results;
      }, 1000);
    },
    // 清除搜索
    clearSearch() {
      this.searchKeyword = '';
      this.searchResults = [];
    },
    // 选择搜索结果
    selectSearchResult(item) {
      this.latitude = item.latitude;
      this.longitude = item.longitude;
      this.locationName = item.name;
      this.locationAddress = item.address;
      this.selectedLocation = item;
      this.searchResults = [];
      
      // 解析地址获取省市区信息
      const addressInfo = this.parseAddress(item.address);
      this.province = addressInfo.province;
      this.city = addressInfo.city;
      this.district = addressInfo.district;
      
      // 更新地图视图
      const mapContext = uni.createMapContext('myMap');
      mapContext.moveToLocation({
        latitude: item.latitude,
        longitude: item.longitude
      });
      
      // 更新标记
      this.updateMarker(item.latitude, item.longitude);
    },
    // 确认选择位置
    confirmLocation() {
      const location = {
        name: this.locationName,
        address: this.locationAddress,
        latitude: this.latitude,
        longitude: this.longitude,
        province: this.province,
        city: this.city,
        district: this.district
      };
      
      // 将选择的位置信息传回上一页
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      if (prevPage) {
        // 调用上一页的方法，传递位置信息
        prevPage.$vm.setLocationInfo && prevPage.$vm.setLocationInfo(location);
      }
      
      uni.navigateBack();
    }
  }
}
</script>

<style lang="scss" scoped>
.map-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  position: relative;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #0088ff;
  color: #fff;
  padding: 0 30rpx;
  position: relative;
  z-index: 10;
}

.nav-back {
  font-size: 40rpx;
  width: 60rpx;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
}

.nav-right {
  width: 80rpx;
  text-align: right;
  font-size: 32rpx;
}

/* 搜索框 */
.search-box {
  padding: 20rpx 30rpx;
  background-color: #fff;
  z-index: 10;
}

.search-input-wrap {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  height: 80rpx;
}

.search-icon {
  font-size: 36rpx;
  color: #999;
  margin-right: 10rpx;
}

.search-input {
  flex: 1;
  height: 80rpx;
  font-size: 28rpx;
}

.clear-icon {
  font-size: 40rpx;
  color: #999;
  padding: 0 10rpx;
}

/* 地图 */
.map {
  flex: 1;
  width: 100%;
}

/* 中心点标记 */
.center-marker {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 5;
  pointer-events: none;
}

.marker-pin {
  width: 30rpx;
  height: 30rpx;
  background-color: #fff;
  border: 4rpx solid #0088ff;
  border-radius: 50%;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.3);
}

.marker-pin::after {
  content: '';
  position: absolute;
  bottom: -20rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 10rpx solid transparent;
  border-right: 10rpx solid transparent;
  border-top: 20rpx solid #0088ff;
}

/* 定位按钮 */
.location-btn {
  position: absolute;
  right: 30rpx;
  bottom: 300rpx;
  width: 80rpx;
  height: 80rpx;
  background-color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
  z-index: 5;
}

.location-btn-icon {
  font-size: 40rpx;
}

/* 位置信息面板 */
.location-panel {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 10;
  max-height: 60vh;
  display: flex;
  flex-direction: column;
}

.current-location {
  display: flex;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.location-icon {
  font-size: 40rpx;
  margin-right: 20rpx;
}

.location-info {
  flex: 1;
}

.location-name {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.location-address {
  font-size: 28rpx;
  color: #666;
}

/* 位置列表 */
.location-list {
  max-height: 50vh;
}

.location-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.item-name {
  font-size: 30rpx;
  margin-bottom: 10rpx;
}

.item-address {
  font-size: 26rpx;
  color: #666;
}
</style>